package Tree;

public class BinaryTrees {
    static int n0 = 0;  //用于保存度为0的结点
    static int n2 = 0;  //用于保存度为2的结点

    public static <T extends Comparable<? super T>> void property3(BinaryTree<T> bitree) {
        BinaryNode<T> root = bitree.getRoot();  //为了对整棵树进行遍历，需要获取树的根节点
        getProperty(root);
        System.out.println("n0的节点为" + n0 + "个，n2结点个数为" + n2 + "，是否符合性质三：n0=n2+1:" + (n0==(n2+1)));
    }

    private static <T extends Comparable<? super T>> void getProperty(BinaryNode<T> root) {
        if (root != null) {
            if (root.left != null && root.right != null) n2++;  //左右结点都存在
            if (root.left == null && root.right == null) n0++;  //左右结点都为空
            getProperty(root.left);
            getProperty(root.right);
        }
    }

    //按照先序的顺序交换左右结点
    public static <T extends Comparable<? super T>> void preSwap(BinaryTree<T> bitree) {
        BinaryNode<T> root = bitree.getRoot();
        if (root != null) {
            preSwap(root);
        } else System.out.println("该树为一棵空树");
    }

    private static <T extends Comparable<? super T>> void preSwap(BinaryNode<T> root) {
        if (root != null) {
            BinaryNode<T> temp = root.left;
            root.left = root.right;
            root.right = temp;
            if (root.left != null) preSwap(root.left);
            if (root.right != null) preSwap(root.right);
        }
    }

    //按照中序的顺序交换左右结点
    public static <T extends Comparable<? super T>> void inSwap(BinaryTree<T> bitree) {
        BinaryNode<T> root = bitree.getRoot();
        if (root != null){
            inSwap(root);
        }else System.out.println("该树为一棵空树");
    }

    private static <T extends Comparable<? super T>> void inSwap(BinaryNode<T> root) {
        if (root != null) {
            if (root.left != null) inSwap(root.left);
            BinaryNode<T> temp = root.left;
            root.left = root.right;
            root.right = temp;
            if (root.right != null) inSwap(root.left);

        }
    }

    //按照后序的顺序交换左右结点
    public static <T extends Comparable<? super T>> void postSwap(BinaryTree<T> bitree) {
        BinaryNode<T> root = bitree.getRoot();
        if (root != null){
            postSwap(root);
        }else System.out.println("该树为一棵空树");
    }

    private static <T extends Comparable<? super T>> void postSwap(BinaryNode<T> root) {
        if (root != null) {
            if (root.left != null) postSwap(root.left);
            if (root.right != null) postSwap(root.right);
            BinaryNode<T> temp = root.left;
            root.left = root.right;
            root.right = temp;
        }
    }


}
